package com.strongbj.iot.devices.newlight.common;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.newlight.request.handle.ActiveTagHandle;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

/**
 * 单线程化的线程池，用户单线程下发任务
 * 
 * @author lei_w
 *
 */
public class Executer {

	// 创建一个单线程化的线程池
	public static ExecutorService pool = Executors.newSingleThreadExecutor();

	public static Thread currentThread;

	public static int currentSequence;

	private static int count = 0;
	private static Logger logger = LogManager.getLogger(Executer.class.getName());

	class CmdTread extends Thread {

		private String cmdType;
		private String readerIp;
		private ByteBuf bf;
		private Map<String, Object> args;
		private byte[] sequence;
		public CmdTread(String cmdType, String readerIp, ByteBuf bf, Map<String, Object> args, byte[] sequence) {
			this.cmdType = cmdType;
			this.readerIp = readerIp;
			this.bf = bf;
			this.args = args;
			this.sequence = sequence;
			count++;
		}

		@Override
		public void run() {
			try {
				currentSequence = ByteUtil.byteArrayToInt(sequence);
				currentThread = Thread.currentThread();
				Channel channel = NetMapping.getInstance().getChannel(readerIp);
				logger.info("当前向硬件发送队列命令的待执行线程数:{} 设备IP{} 命令类型:{}",count--,readerIp,cmdType);
				if(channel==null || channel.isActive()==false) {
					return;
				}
				ChannelFuture cf = channel.writeAndFlush(bf);
				cf.addListener(new ChannelFutureListener() {

					@Override
					public void operationComplete(ChannelFuture future) throws Exception {
						
						switch (cmdType) {
						// 标签点亮
						case "ActiveTag":
							if (future.isSuccess()) {
								logger.info("发送点亮命令成功 设备编号:{} 标签编号:{} 命令={}  ", args.get("code"),
										JSON.toJSONString(args.get("shortTags"), true),
										ByteUtil.byteArrToHexString((byte[]) args.get("req"), true));

								ActiveTagHandle.activeTagMap.put(
										ByteUtil.byteArrToHexString(sequence) + args.get("code"),
										(List<String>) args.get("shortTags"));
							} else {
								logger.debug("发送点亮命令失败 设备编号:{} 标签编号:{} 命令={}  ", args.get("code"),
										JSON.toJSONString(args.get("shortTags"), true),
										ByteUtil.byteArrToHexString((byte[]) args.get("req"), true));
							}
							break;
							// 标签绑定
						case "BindTag":
							if (future.isSuccess()) {
								logger.info("发送绑签命令成功 设备编号:{} 标签编号:{} 命令={}  ", args.get("code"), args.get("tag"),
										ByteUtil.byteArrToHexString((byte[]) args.get("req"), true));
							} else {
								logger.debug("发送绑签命令失败 设备编号:{} 标签编号:{} 命令={}  ", args.get("code"), args.get("tag"),
										ByteUtil.byteArrToHexString((byte[]) args.get("req"), true));
							}
							break;
						}
					}

				});
				Thread.sleep(40000);
				Thread.currentThread().stop();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 发送读写器命令
	 * 
	 * @param cmdType  命令类型
	 * @param readerIp 读写器IP
	 * @param bf       命令流
	 */
	public static void RunCmd(String cmdType, String readerIp, ByteBuf bf, Map<String, Object> args, byte[] sequence) {
		Executer.CmdTread cmd = new Executer().new CmdTread(cmdType, readerIp, bf, args, sequence);
		pool.execute(cmd);

	}

	public static void main(String[] args) {
		// Executer.RunCommand();
	}
}
